<template>
      <div id="users">
            <el-card>
                  <div slot="header">用户管理</div>
                  <div>
                        <!-- 用户信息展示部分 begin -->
                        <el-table :data="tableData" style="width: 100%" v-loading="treeLoading" stripe>
                              <el-table-column prop="username" label="用户名" width="180">
                              </el-table-column>
                              <el-table-column prop="phone" label="手机" width="180" align="center">
                              </el-table-column>
                              <el-table-column prop="email" label="邮箱" align="center">
                              </el-table-column>
                              <el-table-column prop="" label="操作" align="center">

                                    <el-dropdown @command="select" slot-scope="{row}">
                                          <span class="el-icon-more" style="transform:rotate(90deg)"></span>
                                          <el-dropdown-menu slot="dropdown">
                                                <el-dropdown-item :command="{type:'edit',data:row}"><i class="el-icon-edit"></i> 编辑</el-dropdown-item>
                                                <el-dropdown-item :command="{type:'delete',id:row.id}"><i class="el-icon-delete"></i> 删除</el-dropdown-item>
                                                <el-dropdown-item :command="{type:'reset',id:row.id}"><i class="el-icon-setting"></i> 重置密码</el-dropdown-item>
                                          </el-dropdown-menu>
                                    </el-dropdown>
                              </el-table-column>
                        </el-table>
                        <el-pagination style="margin-top:30px" :page-size="pagesize" :page-sizes="[1,2,5,10,15]" @size-change="onchange"  @current-change="getUsersList" :current-page.sync="currentPage" layout=" prev, pager, next,sizes,total" :total="total">
                        </el-pagination>
                        <!-- 用户信息展示部分 end -->
                        
                  </div>
            </el-card>

            <!-- 用户信息对话框 begin-->
            <el-dialog title="编辑" :visible.sync="dialogVisible" width="400px" @close="resetForm()">
                  <el-form ref="formData" :model="formData" label-width="80px" label-position="left" :rules="rules">
                        <el-form-item label="用户名" prop="username">
                              <el-input v-model="formData.username"></el-input>
                        </el-form-item>
                        <el-form-item label="手机" prop="phone">
                              <el-input v-model="formData.phone"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱" prop="email">
                              <el-input v-model="formData.email"></el-input>
                        </el-form-item>
                  </el-form>
                  <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false;">取 消</el-button>
                        <el-button type="primary" :icon="btnIcon" :disabled="buttonDisabled" @click="usersEditComfire">确 定</el-button>
                  </span>
            <!-- 用户信息对话框 end-->
                  
            </el-dialog>
      </div>
</template>
<script>
export default {
  data() {
      //   验证手机格式是否正确
        var validatePhone = (rule, value, cb) => {
            let reg=/^1[3456789]\d{9}$/
            if (reg.test(value)) {
                  cb();
            } else {
                  cb(new Error('手机号码不正确'));
            }
    };
      //   验证用户名是否注册  
    var usernameExist=(rule,value,cb)=>{
        this.$http.post('/users/usernameExist',this.$qs.stringify(this.formData)).then((result)=>{
            if(result.data.data=='false'){
                  cb()
              }else{
                    cb(new Error('用户名已被注册'))
              }
        })
      };
      // 验证手机是否注册
       var phoneExist=(rule,value,cb)=>{
        this.$http.post('/users/phoneExist',this.$qs.stringify(this.formData)).then((result)=>{
            if(result.data.data=='false'){
                  cb()
              }else{
                    cb(new Error('手机已被注册'))
              }
        })
      };
      // 验证邮箱是否注册
      var emailExist=(rule,value,cb)=>{
        this.$http.post('/users/emailExist',this.$qs.stringify(this.formData)).then((result)=>{
            if(result.data.data=='false'){
                  cb()
              }else{
                    cb(new Error('邮箱已被注册'))
              }
        })
      };
    return {
      tableData: [],
      total: 0,
      currentPage:1,
      pagesize:5,
      currentPage:1,
      dialogVisible:false,
      btnIcon:'',
      buttonDisabled:false,
      treeLoading:false,
      formData:{
            username:'',
            phone:'',
            email:'',
            id:'',
            oldname:'',
            oldphone:'',
            oldemail:''
      },
      rules:{
            username:[
                  {required:true,message:'请输入用户名',trigger:'blur'},
                  { min: 4, max: 18, message: "长度在4~18位间", trigger: "change" },
                  {validator:usernameExist, trigger: "blur" },
            ],
            phone:[
                  {required:true,message:'请输入手机号码',trigger:'blur'},
                  {validator:phoneExist, trigger: "blur" },
                  {validator:validatePhone,trigger:'blur'},
            ],
            email:[
                  {required:true,message:'请输入邮箱',trigger:'blur'},
                  {type:'email',message:'邮箱格式有误',trigger:["blur","change"]},
                  {validator:emailExist, trigger: "blur" },
                  
            ]
      }
    };
  },
  methods: {
      //   pagesize改变时的方法
      onchange(val){
            this.pagesize=val
            this.getUsersList()
      },
      // 获取用户信息方法
    getUsersList() {
            this.treeLoading=true
            this.$http.get(`/users/list?pagesize=${this.pagesize}&currentpage=${this.currentPage}`).then(result => {
                  if (result.data.error > 0 &&result.data.error==4) {
                        this.$router.push('/users/login')
                        return
                  }
                  this.treeLoading=false
                  this.tableData = result.data.data;
                  this.total=result.data.total
            }).catch(error=>{
                  console.log(error)
            });
    },
      // 操作方法    
    select(obj){
          switch(obj.type){
                case 'edit':
                  this.usersEdit(obj.data);
                break;
                case 'delete':
                  this.usersDelete(obj.id)
                break;
                case 'reset':
                  this.passwordReset(obj.id)
                break;
                default:;
          }
    },
      //  删除用户信息方法   
    usersDelete(id){
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
            }).then(() => {
                  this.$http.get(`/users/delete?id=${id}`).then(result=>{
                        if(result.data.error==0){
                              this.getUsersList()
                              this.$message({
                              type: 'success',
                              message: '删除成功!'}) 
                        }else{
                              this.$message({
                              type: 'danger',
                              message: '删除失败!'})
                        }
                  }).catch(error=>{
                        console.log(error)
                  }) ;
            })   
    },
      //  编辑用户信息方法
      usersEdit(row){
            this.dialogVisible=true
            this.formData.username=row.username
            this.formData.phone=row.phone
            this.formData.email=row.email
            this.formData.id=row.id
            this.formData.oldname=row.username
            this.formData.oldphone=row.phone
            this.formData.oldemail=row.email
      },
      
      // 编辑确认
      usersEditComfire(){
            this.$refs.formData.validate(pass => {
                  if (!pass) { return}
                  this.btnIcon='el-icon-loading'
                  this.buttonDisabled=true   
                  this.$http.post("/users/edit", this.$qs.stringify(this.formData)).then(result => {
                        if(result.data.error==0){
                              this.btnIcon=''
                              this.buttonDisabled=false  
                              this.getUsersList()
                              this.dialogVisible=false
                        }
                  }).catch(error=>{
                        console.log(error)
                  });
       
      });
      },
      // 重置密码方法
      passwordReset(id){
            this.$confirm('重置密码为123456, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
            }).then(() => {
                  this.$http.get(`/users/passwordReset?id=${id}`).then(result=>{
                        if(result.data.error==0){
                              this.getUsersList()
                              this.$message({
                              type: 'success',
                              message: '重置密码成功!'}) 
                        }else{
                              this.$message({
                              type: 'danger',
                              message: '重置密码失败!'})
                        }
                  }).catch(error=>{
                        console.log(error)
                  }) ;
            })   
      },
         //  重置表单的方法   
      resetForm() {
            this.$refs.formData.resetFields();
            this.formData.pid=0
      },
     

  },
  created() {
      //   调用获取用户信息方法
    this.getUsersList();
  }
};
</script>
<style>
</style>


